package report_log

import (
	"bufio"
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"time"
)

func getAllReqData(filePath, name string) {

	lines := ReadLine(filePath)
	tranceIds := make(map[string][]int64)

	for _, line := range lines {
		if line.TraceId != "" {
			//date, _ := time.Parse("2006-01-02 15:04:05.000", line.Time)
			tranceIds[line.TraceId] = append(tranceIds[line.TraceId], getTimeUnix(line.Time))
		}
	}

	tj := make(map[int64]int)
	tIds := make(map[string]int64)
	for id, val := range tranceIds {
		tj[getTimeLen(val)]++
		tIds[id] = getTimeLen(val)
	}

	tj2 := make(map[string]interface{})
	for k, v := range tj {
		tmp := strconv.Itoa(int(k))
		tj2[tmp] = v
	}

	//jsonStr, _ := json.Marshal(tj)
	//val := string(jsonStr)
	NewRds().HMSet("map:" + name, tj2)
	getLogger(name).Println(tIds)
}

func getTimeUnix(dateStr string) int64 {
	date, _ := time.Parse("2006-01-02 15:04:05.000", dateStr)
	return date.Unix()
}

func getTimeLen(times []int64) int64 {
	var max int64 = 0
	var min int64 = 1 << 32

	for _, val := range times {
		if val > max {
			max = val
		}

		if val < min {
			min = val
		}
	}
	return max - min
}


func ReadLine(filePath string) []Line {
	file, err := os.Open(filePath)
	if err != nil{
		fmt.Println(err.Error())
		panic("file error")
	}
	defer file.Close()
	fd:=bufio.NewReader(file)
	count :=0
	lines := make([]Line, 0)
	for {
		str ,err := fd.ReadString('\n')
		if err!= nil {
			fmt.Println(err.Error())
			break
		}
		tmp := Line{}
		err2 := json.Unmarshal([]byte(str), &tmp)
		if err2 != nil {
			fmt.Println("json解析失败", err.Error())
			continue
		}
		lines = append(lines, tmp)
		//fmt.Println(count, str)
		count++
	}
	//fmt.Println(lines[:1])
	fmt.Println(count)
	return lines
}

type Line struct {
	Level   string `json:"level"`
	Msg     string `json:"msg"`
	Time    string `json:"time"`
	TraceId string `json:"traceId"`
	Batch   string `json:"batch"`
}


func getBatchTime(filePath string) map[string]int64 {
	lines := ReadLine(filePath)

	batchs := make(map[string][]int64)
	for _, line := range lines {
		if line.Batch != "" {
			batchs[line.Batch] = append(batchs[line.Batch], getTimeUnix(line.Time))
		}
	}

	batchLen := make(map[string]int64)
	for k, batch := range batchs {
		batchLen[k] = getTimeLen(batch)
	}

	return batchLen
}

